<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>菜单管理</el-breadcrumb-item>
			<el-breadcrumb-item>菜单列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card>
			<!-- 植入搜索栏 -->
			<el-row :gutter="20">
				<el-col :span="5"><el-input clearable placeholder="搜索名称" v-model="searchMenuName" clearableclear="getMenuList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索路径" v-model="searchPath" clearableclear="getMenuList"></el-input></el-col>

				<el-col :span="2">
					<el-button type="primary" @click="getMenuList()">
						<el-icon><Search /></el-icon>
					</el-button>
				</el-col>
				<el-col :span="5"><el-button type="primary" @click="showAddBox = true">添加菜单</el-button></el-col>
			</el-row>
			<!-- 放入table -->
			<el-table
				:data="tableData"
				style="width: 100%; height: 550px; margin-top:10px;"
				border
				:header-cell-style="{ height: '37px', padding: '0' }"
				:row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
				row-key="id"
			>
				<!-- 数据绑定 -->
				<el-table-column fixed label="菜单id" width="100" prop="id"></el-table-column>
				<el-table-column fixed label="路由名称" width="100" prop="name"></el-table-column>
				<el-table-column label="父级菜单id" width="120" prop="parentId"></el-table-column>
				<el-table-column label="菜单名称" width="120" prop="menuName"></el-table-column>
				<el-table-column label="路径" width="150" prop="path"></el-table-column>
				<el-table-column label="组件地址" width="150" prop="component"></el-table-column>
				<el-table-column label="图标" width="120" prop="icon"></el-table-column>
				<el-table-column label="可用性" width="100" prop="enable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, true)" class="el-col-sm-22" size="small" v-model="scope.row.enable">
							<el-option v-for="item in enableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="是否锁定" width="100" prop="lockable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, false)" class="el-col-sm-22" size="small" v-model="scope.row.lockable">
							<el-option v-for="item in lockableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column label="创建者" width="80" prop="createBy"></el-table-column>
				<el-table-column label="创建时间" width="200" prop="createDate"></el-table-column>
				<el-table-column label="最近修改人" width="100" prop="updateBy"></el-table-column>

				<el-table-column label="最近修改" width="200" prop="lastUpdate"></el-table-column>

				<el-table-column fixed="right" label="操作" width="150">
					<template #default="scope">
						<el-button size="small" @click="showEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页模块 -->
			<el-pagination
				v-model:current-page="pageNo"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:small="false"
				:disabled="false"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="totalCount"
				@size-change="onSizeChange"
				@current-change="onPageChange"
			/>

			<!-- 添加会话框 -->
			<el-dialog title="添加菜单对话框" v-model="showAddBox" width="30%" :before-close="onClose" style="padding: 8px 15px;" @close="onClose" :draggable="true">
				<el-form :model="menuForm" :rules="menuFormRules" ref="menuFormRules" label-width="120px">
					<el-form-item label="路由名称" prop="name"><el-input v-model="menuForm.name"></el-input></el-form-item>

					<el-form-item label="父级ID" prop="parentId">
						<el-select @change="setPath" v-model="menuForm.parentId" filterable allow-create default-first-option :reserve-keyword="false" placeholder="选择或新建父ID">
							<el-option v-for="item in fatherOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>

					<el-form-item label="菜单名称" prop="menuName"><el-input v-model="menuForm.menuName"></el-input></el-form-item>

					<el-form-item label="路径" prop="path">
						<el-input v-model="menuForm.path">
							<template #prepend>
								{{ fatherPath }}
							</template>
						</el-input>
					</el-form-item>

					<el-form-item label="组件" prop="component">
						<template #default="scope">
							<el-input v-if="fatherFlag == 1" disabled v-model="menuForm.component" placeholder="父级路径不需要设置组件"></el-input>
							<el-input v-else v-model="menuForm.component"></el-input>
						</template>
						<!-- <el-input v-model="menuForm.component"></el-input> -->
					</el-form-item>
					<!-- <el-form-item label="图标" prop="icon"><el-input v-model="menuForm.icon"></el-input></el-form-item> -->
					<el-form-item label="图标" prop="icon">
						<el-select
							v-if="fatherFlag == 1"
							@change="setIcon"
							v-model="menuForm.icon"
							filterable
							default-first-option
							:reserve-keyword="false"
							placeholder="选择菜单图标"
						>
							<el-option v-for="item in iconList" :key="item" :label="item" :value="item">
								<component class="icons" :is="item" style="padding-right: 20%; width: 20px;"></component>
								<span>{{ item }}</span>
							</el-option>
						</el-select>
						<el-input v-else disabled v-model="menuForm.icon" placeholder="子路径不需要设置图标"></el-input>
					</el-form-item>
					<el-form-item class="dialog-footer">
						<el-button @click="onClose">取消</el-button>
						<el-button type="primary" @click="saveMenuData('menuFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

			<!-- 编辑会话框 -->
			<el-dialog title="编辑菜单" v-model="showEditBox" width="30%" :before-close="onClose" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="menuForm" :rules="menuFormRules" ref="menuFormRules" label-width="120px">
					<!-- --- [添加其它同类项]开始 --- -->
					<!-- 记得修改prop和下面的v-model[menuForm.xxx] -->

					<el-form-item label="路由名称" prop="name"><el-input v-model="menuForm.name"></el-input></el-form-item>

					<el-form-item label="父级ID" prop="parentId">
						<el-select @change="setPath" v-model="menuForm.parentId" filterable allow-create default-first-option :reserve-keyword="false" placeholder="选择或新建父ID">
							<el-option v-for="item in fatherOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
						<!-- <el-input v-model="menuForm.parentId"></el-input> -->
					</el-form-item>

					<el-form-item label="菜单名称" prop="menuName"><el-input v-model="menuForm.menuName"></el-input></el-form-item>

					<el-form-item label="路径" prop="path">
						<el-input v-model="menuForm.path">
							<template #prepend>
								{{ fatherPath }}
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="组件" prop="component">
						<template #default="scope">
							<el-input v-if="menuForm.parentId == 'top'" disabled v-model="menuForm.component" placeholder="父级路径不需要设置组件"></el-input>
							<el-input v-else v-model="menuForm.component"></el-input>
						</template>
						<!-- <el-input v-model="menuForm.component"></el-input> -->
					</el-form-item>

					<el-form-item label="图标" prop="icon">
						<el-select
							v-if="menuForm.parentId == 'top'"
							@change="setIcon"
							v-model="menuForm.icon"
							filterable
							default-first-option
							:reserve-keyword="false"
							placeholder="选择菜单图标"
						>
							<el-option v-for="item in iconList" :key="item" :label="item" :value="item">
								<component class="icons" :is="item" style="padding-right: 20%; width: 20px;"></component>
								<span>{{ item }}</span>
							</el-option>
						</el-select>
						<el-input v-else disabled placeholder="子路径不需要设置图标" v-model="menuForm.icon"></el-input>
						<!-- <el-input v-model="menuForm.icon"></el-input> -->
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="onClose">取消</el-button>
					<el-button type="primary" @click="handleEdit(menuForm.id, 'menuFormRules')">确定</el-button>
				</span>
			</el-dialog>
		</el-card>
	</div>
</template>

<script>
import { getMenuList, addMenu, deleteMenu } from '@/api/menu.js';
import * as elementPlusIconList from '@element-plus/icons-vue';
export default {
	data() {
		return {
			iconList: [],
			fatherOptions: [],
			fatherPath: '',
			fatherFlag: 0,

			enableOptions: [
				{
					value: '0',
					label: '是'
				},
				{
					value: '1',
					label: '否'
				}
			],
			lockableOptions: [
				{
					value: '1',
					label: '是'
				},
				{
					value: '0',
					label: '否'
				}
			],
			showEditBox: false,
			showAddBox: false,
			searchStr: '',
			pageNo: 1,
			pageSize: 999,
			totalCount: 0,
			searchPath: '',
			searchMenuName: '',
			// menuList: [],
			menuForm: [],
			tableData: [],
			trigger: 'blur',

			menuFormRules: {
				parentId: [{ required: true, message: '请选择或输入新的父级菜单', trigger: 'blur' }],
				name: [
					{ required: true, message: '请输入路由名称', trigger: 'blur' },
					{
						required: true,
						pattern: /^[A-Za-z]+$/,
						message: '路由名称仅能由字母组成',
						trigger: 'blur'
					}
				],
				menuName: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
				path: [
					{
						required: true,
						message: '请输入指向路径',
						trigger: 'blur'
					}
				],

				icon: [
					{
						required: false,
						pattern: /^[A-Za-z]+$/,
						message: '图标名仅能由字母组成',
						trigger: 'blur'
					}
				]
			}
		};
	},
	methods: {
		setIcon() {},

		setPath() {
			this.fatherPath = '';
			this.fatherFlag = 0;

			this.fatherOptions.forEach(option => {
				if (option.value == this.menuForm.parentId) {
					this.fatherPath = option.path;
				}
			});
			if (this.fatherPath == '') {
				this.fatherPath = "'/your path/'";
				this.fatherFlag = 1;
			}
			// console.log(this.fatherPath);
			// console.log('-------------');
		},
		changeEnableOrLock(row, judge) {
			console.log(row);
			var param = [];
			// console.log(judge);
			if (judge) {
				param = { id: row.id, parentId: row.parentId, enable: row.enable };
			} else {
				param = { id: row.id, parentId: row.parentId, lockable: row.lockable };
			}
			// console.log(param);
			addMenu(param)
				.then(resp => {
					if (resp.success) {
						this.$message({
							type: 'success',
							message: '已修改'
						});
					} else {
						this.$message({
							type: 'error',
							message: '修改失败' + resp.message
						});
					}
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '修改失败' + ex
					});
				});
		},

		onClose() {
			this.menuForm = [];
			this.fatherPath = '';
			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},
		getMenuList() {
			this.searchStr = {
				menuName: this.searchMenuName,
				path: this.searchPath
			};
			const param = { page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr };

			getMenuList(param).then(resp => {
				this.totalCount = resp.total;
				this.tableData = resp.rows;
				// console.log('-----------------------');
				// console.log(this.tableData);
				if ((this.fatherOptions = [])) {
					this.tableData.forEach(list => {
						const fatherMap = { value: list.id, label: list.menuName, path: list.path };
						this.fatherOptions.push(fatherMap);
					});
				}
			});
		},
		saveMenuData(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					console.log('验证通过');
					this.$confirm('此操作将添加菜单, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							const param = {
								id: '',
								name: this.menuForm.name,
								parentId: this.menuForm.parentId,
								menuName: this.menuForm.menuName,
								path: '',
								component: this.menuForm.component,
								icon: this.menuForm.icon
							};
							const inputPath = this.menuForm.path;

							if (typeof param.parentId == 'number') {
								// console.log('这里是子级id');
								if (inputPath.charAt('0') == '/') {
									this.$message({
										type: 'error',
										message: '输入格式不正确！子级路径首字母不能为( / )---：' + inputPath
									});
								} else if (inputPath.split('\/').pop() == '') {
									this.$message({
										type: 'error',
										message: '输入格式不正确！子级路径首字母不能为( / )---：' + inputPath
									});
								} else {
									param.path = this.fatherPath + inputPath;
								}
							} else {
								// console.log('这里是父级id');
								if (inputPath.charAt('0') != '/') {
									this.$message({
										type: 'error',
										message: '输入格式不正确！父级路径首字母需为( / )---：' + inputPath
									});
								} else if (inputPath.split('\/').pop() != '') {
									this.$message({
										type: 'error',
										message: '输入格式不正确！父级路径末尾字母需为( / )---：' + inputPath
									});
								} else {
									param.parentId = 'top';
									param.path = inputPath;
								}
							}
							addMenu(param).then(resp => {
								this.onClose();
								window.sessionStorage.removeItem('MENUS');
								this.getMenuList();

								this.fatherOptions = [];
							});
						})
						.catch(() => {
							// console.log(message)
							this.$message({
								type: 'error',
								message: '已取消添加'
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		},
		showEdit(row) {
			//设置id
			this.menuForm.id = row.id;
			// console.log('row.id-----' + row.id);
			//设置表单默认值
			// console.log('这里是showEdit-----------------');
			var sonPath = '';

			this.tableData.forEach(item => {
				if (item.id == row.parentId) {
					// console.log(item.path);
					this.fatherPath = item.path;
					sonPath = row.path;

					sonPath = sonPath.substring(this.fatherPath.length);
					this.menuForm.path = sonPath;

					// console.log('>>>>>>>>>>>>>>>>>>>' + sonPath);
				}
			});
			if (this.fatherPath == '') {
				this.fatherPath = '此为父级路径--->';
				this.menuForm.path = row.path;
			}

			//设置表单默认值
			this.menuForm.name = row.name;
			this.menuForm.parentId = row.parentId;
			this.menuForm.menuName = row.menuName;
			this.menuForm.icon = row.icon;
			this.menuForm.component = row.component;

			//弹框
			this.showEditBox = true;
		},
		handleDelete(index, deleteId) {
			this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					const delId = { id: deleteId };
					// console.log(delId);
					deleteMenu(deleteId).then(resp => {
						if (resp.success) {
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
						}
						this.getMenuList();
					});
				})
				.catch(() => {
					this.$message({
						type: 'error',
						message: '删除失败！'
					});
				});
		},
		//  ---确认函数
		handleEdit(editId, formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.$confirm('此操作将修改该菜单, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})

						.then(() => {
							// console.log(editId);
							const param = {
								id: editId,
								name: this.menuForm.name,
								parentId: this.menuForm.parentId,
								path: '',
								menuName: this.menuForm.menuName,
								icon: this.menuForm.icon,
								component: this.menuForm.component,
								isEdit: true
							};
							// console.log(param);
							if (param.parentId != 'top') {
								param.path = this.fatherPath + this.menuForm.path;
							} else {
								param.path = this.menuForm.path;
							}
							// console.log(param);
							addMenu(param).then(resp => {
								this.$message({
									type: 'success',
									message: '修改成功!'
								});
								window.sessionStorage.removeItem('MENUS');
								this.onClose();
								this.getMenuList();
							});
						})
						.catch(() => {
							this.$message({
								type: 'error',
								message: '修改失败！'
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		},
		onSizeChange(pageSize) {
			this.pageNo = 1;
			this.pageSize = pageSize;
			this.getMenuList();
		},
		onPageChange(page) {
			this.pageNo = page;
			this.getMenuList();
		}
	},
	mounted() {
		for (const [component] of Object.entries(elementPlusIconList)) {
			this.iconList.push(component);
		}
		this.getMenuList();
	}
};
</script>

<style scoped>
div.el-breadcrumb {
	height: 45px;
}

.el-dialog__body {
	padding: 0px 15px;
}
</style>
